import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../view/Login/Login.vue'
import Reg from '../view/Reg/Reg.vue'
// 1. 导入后台主页组件
import Main from '../view/Main/Main.vue'
import store from '../store'
import Home from '@/view/Menus/Home/Home.vue'
import UserInfo from '@/view/Menus/User/UserInfo.vue'
import UserAvatar from '@/view/Menus/User/UserAvatar.vue'
import UserPwd from '@/view/Menus/User/UserPwd.vue'
import ArtCate from '@/view/Menus/Article/Article.vue'
import ArticleList from '@/view/Menus/Article/ArticleList.vue'

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    // 3. 开启路由重定向
    redirect: '/home',
    children: [
      // 2. home 作为 子路由规则
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArticleList }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/' && !store.state.token) {
    Vue.prototype.$message.error('请登录!')
    next('/login')
  }
  next()
})

export default router
